//package com.example.search.service.impl;
//
//import com.alibaba.fastjson.JSON;
//import com.example.model.common.dtos.ResponseResult;
//import com.example.model.common.enums.AppHttpCodeEnum;
//import com.example.model.search.dtos.UserSearchDto;
//import com.example.search.service.ArticleSearchService;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang.StringUtils;
//import org.elasticsearch.action.search.SearchRequest;
//import org.elasticsearch.action.search.SearchResponse;
//import org.elasticsearch.client.RequestOptions;
//import org.elasticsearch.client.RestHighLevelClient;
//import org.elasticsearch.common.text.Text;
//import org.elasticsearch.index.query.*;
//import org.elasticsearch.search.SearchHit;
//import org.elasticsearch.search.builder.SearchSourceBuilder;
//import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
//import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
//import org.elasticsearch.search.sort.SortOrder;
//import org.jsoup.helper.StringUtil;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//
//import java.io.IOException;
//import java.util.ArrayList;
//import java.util.List;
//import java.util.Map;
//
//@Service
//@Slf4j
//public class ArticleSearchServiceImpl implements ArticleSearchService {
//
//    @Autowired
//    private RestHighLevelClient restHighLevelClient;
//
//    @Override
//    public ResponseResult search(UserSearchDto dto) {
//
//        if(dto == null || StringUtil.isBlank(dto.getSearchWords())){
//            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
//        }
//
//        SearchRequest searchRequest = new SearchRequest("app_info_article");
//        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//
//
//        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
//
//        QueryStringQueryBuilder queryStringQueryBuilder = QueryBuilders.queryStringQuery(dto.getSearchWords()).field("title").field("content").defaultOperator(Operator.OR);
//        boolQueryBuilder.must(queryStringQueryBuilder);
//
//        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime().getTime());
//        boolQueryBuilder.filter(rangeQueryBuilder);
//
//        searchSourceBuilder.from(0);
//        searchSourceBuilder.size(dto.getPageSize());
//
//        searchSourceBuilder.sort("publishTime", SortOrder.DESC);
//
//        HighlightBuilder highlightBuilder = new HighlightBuilder();
//        highlightBuilder.preTags("<font style='color: red; font-size: inherit;'>");
//        highlightBuilder.postTags("</font>");
//        searchSourceBuilder.highlighter(highlightBuilder);
//
//
//        searchSourceBuilder.query(boolQueryBuilder);
//        searchRequest.source(searchSourceBuilder);
//
//        SearchResponse searchResponse = null;
//
//        try {
//            searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//        List<Map> list = new ArrayList<>();
//
//        SearchHit[] searchHits = searchResponse.getHits().getHits();
//        for (SearchHit searchHit : searchHits){
//            String json = searchHit.getSourceAsString();
//            Map map = JSON.parseObject(json, Map.class);
//
//            if(searchHit.getHighlightFields() != null && searchHit.getHighlightFields().size() > 0){
//                Text[] titles = searchHit.getHighlightFields().get("title").getFragments();
//                String title = StringUtils.join(titles);
//                map.put("h_title",title);
//            }else {
//                map.put("h_title",map.get("title"));
//            }
//            list.add(map);
//
//        }
//
//        return ResponseResult.okResult(list);
//    }
//}

package com.example.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.example.model.common.dtos.ResponseResult;
import com.example.model.common.enums.AppHttpCodeEnum;
import com.example.model.search.dtos.UserSearchDto;
import com.example.model.user.pojos.ApUser;

import com.example.search.service.ApUserSearchService;
import com.example.search.service.ArticleSearchService;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private ApUserSearchService apUserSearchService;

    /**
     * es文章分页检索
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto,String userId) throws IOException {

        //1.检查参数
        if(dto == null || StringUtils.isBlank(dto.getSearchWords())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        log.info("保存搜索记录");
        if(dto.getFromIndex() == 0){  //首页
            apUserSearchService.insert(dto.getSearchWords(), Integer.valueOf(userId));
        }


        //2.设置查询条件
        SearchRequest searchRequest = new SearchRequest("app_info_article");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        //布尔查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        //关键字的分词之后查询
        QueryStringQueryBuilder queryStringQueryBuilder = QueryBuilders.queryStringQuery(dto.getSearchWords()).field("title").field("content").defaultOperator(Operator.OR);
        boolQueryBuilder.must(queryStringQueryBuilder);

        //查询小于mindate的数据
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime().getTime());
        boolQueryBuilder.filter(rangeQueryBuilder);

        //分页查询
        searchSourceBuilder.from(0);
        searchSourceBuilder.size(1000);

        //按照发布时间倒序查询
        searchSourceBuilder.sort("publishTime", SortOrder.DESC);

        //设置高亮  title
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<font style='color: red; font-size: inherit;'>");
        highlightBuilder.postTags("</font>");
        searchSourceBuilder.highlighter(highlightBuilder);


        searchSourceBuilder.query(boolQueryBuilder);
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);


        //3.结果封装返回

        List<Map> list = new ArrayList<>();

        SearchHit[] hits = searchResponse.getHits().getHits();
        System.out.println("长度 "+hits.length);
        for (SearchHit hit : hits) {
            String json = hit.getSourceAsString();
            Map map = JSON.parseObject(json, Map.class);
            //处理高亮
            if(hit.getHighlightFields() != null && hit.getHighlightFields().size() > 0){
                Text[] titles = hit.getHighlightFields().get("title").getFragments();
                String title = StringUtils.join(titles);
                //高亮标题
                map.put("h_title",title);
            }else {
                //原始标题
                map.put("h_title",map.get("title"));
            }

            list.add(map);
        }

        return ResponseResult.okResult(list);

    }
}
